using System;
using System.Collections.Generic;
using System.Linq;

namespace Flit.Samples.Validation
{
    public abstract class FluentStateBase
    {
        protected FluentStateBase()
        {
            Children = new List<FluentStateBase>();
        }

        public FluentStateBase Parent { get; set; }

        public List<FluentStateBase> Children { get; private set; }

        protected IEnumerable<FluentStateBase> Ancestors()
        {
            FluentStateBase f = this;
            while(f != null)
            {
                yield return f;
                f = f.Parent;
            }
        }

        protected void AddErrorMessage(string error)
        {
            Validation root = Ancestors().OfType<Validation>().Single();
            root.Errors = root.Errors ?? new List<string>();
            root.Errors.Add(error);
        }
        
        protected void AddErrorMessageIf<T>(Predicate<T> test, T value, string name, string description)
        {
            if(test(value))
            {
                AddErrorMessage(string.Format("'{0}' {1} but was {2}", name, description, value));
            }
        }
    }
}